/**
 * 
 */
package com.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.auth.model.Account;
import com.auth.model.Role;
import com.opensymphony.xwork2.ActionSupport;
import com.util.ConfigUtil;
import com.util.ConstantUtil;
import com.util.Province;
import com.util.ProvinceUtil;
import com.util.Region;
import com.util.RegionUtil;

public class AbstractAction extends ActionSupport 
{
	protected Account operator = null;
	protected HttpSession session = null;
	protected HttpServletRequest request = null;
	protected HttpServletResponse response = null;
	
	protected String remoteAddr = null;
	
	public AbstractAction()
	{
		this.operator = (Account) session().getAttribute("account");
		this.session = ServletActionContext.getRequest().getSession();
		this.request = ServletActionContext.getRequest();
		this.response = ServletActionContext.getResponse();
		
		this.remoteAddr = this.request.getRemoteAddr();
		
		// accessLog();
	}
	
//	private void accessLog()
//	{
//		Logger.getLogger("ACCESS").info(request.getRemoteAddr() +
//				" " + request.getMethod() + " " + request.getRequestURI() + 
//				(request.getQueryString() == null ? "" : ("?" + request.getQueryString())) +
//				" " + request.getProtocol());
//	}
	
	public String error()
	{
		// Logger.getLogger("error").error("action not found");
		return null;
	}
	
	public String error404()
	{
		return "error404";
	}
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected HttpSession session() {
		return ServletActionContext.getRequest().getSession();
	}
	
	protected HttpServletRequest getRequest()
	{
		return ServletActionContext.getRequest();
	}

	protected HttpServletResponse getResponse()
	{
		return ServletActionContext.getResponse();
	}
	
	protected InputStream getInputStream()
	{
		try 
		{
			return getRequest().getInputStream();
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	protected String getHeader(String key)
	{
		return getRequest().getHeader(key);
	}
	
	protected void setHeader(String key, String value)
	{
		getResponse().setHeader(key, value);
	}
	
	protected String getContentType()
	{
		return getRequest().getContentType();
	}
	
	protected int getContentLength()
	{
		return getRequest().getContentLength();
	}
	
	protected String getContextPath()
	{
		return getRequest().getContextPath();
	}
	
	protected void setContentType(String contentType)
	{
		getResponse().setContentType(contentType);
	}
	
	protected void setContentLength(int contentLength)
	{
		getResponse().setContentLength(contentLength);
	}
	
	protected void setSession(String key, Object value)
	{
		getRequest().getSession().setAttribute(key, value);
	}
	
	protected Object getSession(String key)
	{
		return getRequest().getSession().getAttribute(key);
	}
	
	protected String getRemoteAddr()
	{
		return getRequest().getRemoteAddr();
	}

	protected String getRemoteHost()
	{
		return getRequest().getRemoteHost();
	}

	protected int getRemotePort()
	{
		return getRequest().getRemotePort();
	}

	protected Map<String, String[]> getParameters()
	{
		return getRequest().getParameterMap();
	}
	
	protected String getParameter(String paramName)
	{
		return getRequest().getParameter(paramName);
	}

	protected Object getAttribute(String paramName)
	{
		return getRequest().getAttribute(paramName);
	}
	
	protected String getRealPath(String path)
	{
		return ServletActionContext.getServletContext().getRealPath(path);
	}

	protected int saveUploadFile(File uploadFile, String savePath) 
	{
		if (savePath.lastIndexOf("/") > 0)
		{
			String s = savePath.substring(0, savePath.lastIndexOf("/"));
			File f = new File(s);
			if (!f.exists())
				f.mkdirs();
		}
		
		int fileLen = 0;
		try
		{
			FileOutputStream fos = new FileOutputStream(savePath);
	        FileInputStream fis = new FileInputStream(uploadFile);
	        byte[] buffer = new byte[1024];
	        int len = 0;
	        while((len = fis.read(buffer))>0)
	        {
	        	fileLen += len;
	            fos.write(buffer, 0, len);
	        }
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}        
        return fileLen;
	}

	public String getConfig(String section, String key)
	{
		return ConfigUtil.get(section, key);
	}
	
	public Map<String, String> getConstant(String type)
	{
		return ConstantUtil.getConstant(type);
	}
	
	public String getConstantString(String type, String key)
	{
		return ConstantUtil.getConstantString(type, key);
	}
	
	public boolean validateMenu(int menuIndex)
	{
		if (menuIndex <= 0)
		{
			return false;
		}
		
		Account account = (Account) getSession("account");
		Role role = (Role) getSession("role");
		if (account != null && role != null
				&& role.getValue().length() >= menuIndex 
				&& role.getValue().charAt(menuIndex-1) == '1')
		{
			return true;
		}
		return false;
	}
	
	public String formatDate(Date date, String fmt)
	{
		Date d = new Date();
		String f = "yyyy-MM-dd HH:mm:ss";
		
		if (date != null)
			d = date;
		if (fmt != null && fmt.length() > 0)
			f = fmt;
		//System.out.println(f);
		SimpleDateFormat sdf = new SimpleDateFormat(f);
		return sdf.format(d);
	}

	public Province getProvince(String code)
	{
		return ProvinceUtil.getInstance().getProvince(code);
	}
	
	public List<Province> getProvinces()
	{
		return ProvinceUtil.getInstance().getProvince();
	}
	
	public Region getRegion(String province, int id)
	{
		return RegionUtil.getInstance().getRegion(province, id);
	}

	public Region getRegion(String province, String code)
	{
		return RegionUtil.getInstance().getRegion(province, code);
	}
	
	public List<Region> getRegions(String province)
	{
		if (province == null || province.length() == 0 
				|| province.equalsIgnoreCase("ALL"))
			return RegionUtil.getInstance().getRegion();
		return RegionUtil.getInstance().getRegion(province);
	}
	
	public String regionToNameString(String province,String regionString)
	{
		String r = "";
		String[] s = regionString.split(",");
		for (String t : s)
		{
			Region p = getRegion(province,t);
			if (p != null)
			{
				if (r.length() > 0)
					r += ",";
				r += p.getName();
			}
		}
		return r;
	}
	
	public String provinceToNameString(String provinceString)
	{
		String r = "";
		String[] s = provinceString.split(",");
		for (String t : s)
		{
			Province p = getProvince(t);
			if (p != null)
			{
				if (r.length() > 0)
					r += ",";
				r += getProvince(t).getName();
			}
		}
		return r;
	}

	public boolean checkQueryDimension(String dimension, String key)
	{
		if (dimension == null)
			return false;
		String d[] = dimension.split(";");
		for (int n = 0; n < d.length; n++)
			if (d[n].equals(key))
				return true;
		return false;
	}
	
	public int getQueryDimensionCount(String dimension)
	{
		if (dimension == null)
			return 0;
		int dc = 0;
		String d[] = dimension.split(";");
		for (int n = 0; n < d.length; n++)
			if (!d[n].equals("false"))
				dc++;
		return dc;
	}
	
	protected String downloadFileRanges(String filePath) {
		// System.out.println("下载时，收到传进来的值：" + filePath);
		System.out.println("download : " + filePath + " range:"
				+ request.getHeader("Range"));

		File file = new File(filePath);
		if (!file.exists()) {
			// 文件不存在
			return null;
		} else {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);

				this.response.setHeader("Accept-Ranges", "bytes");
				long p = 0;
				long l = 0;
				// l = raf.length();
				l = file.length();
				// 如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置
				// 响应的格式是:
				// HTTP/1.1 200 OK
				if (this.request.getHeader("Range") != null) // 客户端请求的下载的文件块的开始字节
				{
					// 如果是下载文件的范围而不是全部,向客户端声明支持并开始文件块下载
					// 要设置状态
					// 响应的格式是:
					// HTTP/1.1 206 Partial Content
					this.response
							.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);// 206
					// 从请求中得到开始的字节
					// 请求的格式是:
					// Range: bytes=[文件块的开始字节]-
					p = Long.parseLong(this.request.getHeader("Range")
							.replaceAll("bytes=", "").replaceAll("-", ""));
				}
				// 下载的文件(或块)长度
				// 响应的格式是:
				// Content-Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节]
				this.response.setHeader("Content-Length",
						new Long(l - p).toString());
				if (p != 0) {
					// 不是从最开始下载,
					// 响应的格式是:
					// Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
					this.response.setHeader("Content-Range",
							"bytes " + new Long(p).toString() + "-"
									+ new Long(l - 1).toString() + "/"
									+ new Long(l).toString());
				}
				// response.setHeader("Connection", "Close"); //如果有此句话不能用 IE
				// 直接下载
				// 使客户端直接下载
				// 响应的格式是:
				// Content-Type: application/octet-stream
				this.response.setContentType("application/octet-stream");
				// 为客户端下载指定默认的下载文件名称
				// 响应的格式是:
				// Content-Disposition: attachment;filename="[文件名]"
				// response.setHeader("Content-Disposition",
				// "attachment;filename=\"" + s.substring(s.lastIndexOf("\\") +
				// 1) +
				// "\""); //经测试 RandomAccessFile 也可以实现,有兴趣可将注释去掉,并注释掉
				// FileInputStream 版本的语句
				this.response.setHeader("Content-Disposition",
						"attachment;filename=" + file.getName() + "");
				// raf.seek(p);
				fis.skip(p);
				byte[] b = new byte[1024];
				int i;
				// while ( (i = raf.read(b)) != -1 ) //经测试 RandomAccessFile
				// 也可以实现,有兴趣可将注释去掉,并注释掉 FileInputStream 版本的语句
				while ((i = fis.read(b)) != -1) {
					this.response.getOutputStream().write(b, 0, i);
					this.response.flushBuffer();
				}
				// raf.close();//经测试 RandomAccessFile 也可以实现,有兴趣可将注释去掉,并注释掉
				// FileInputStream 版本的语句
				fis.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fis != null) {
					try {
						fis.close();
						this.response.getOutputStream().close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}
		}
		return null;
	}

	protected String getInputStreamAsString() {
		String string = "";
		if (request.getContentType() != null 
				&& request.getContentType().startsWith("application/x-www-form-urlencoded"))
		{
			System.out.println("getInputStreamAsString:application/x-www-form-urlencoded");
			Map map = request.getParameterMap();
			Iterator iter = map.keySet().iterator();
			String s = "";
			while (iter.hasNext())
			{
				String key = (String) iter.next();
				String value = request.getParameter(key);
				s +=value;
			}
			string = s.replace("\r", "").replace("\n", "").replace(" ", "+");
//			try
//			{
//				string = URLEncoder.encode(s.replace("\r", "").replace("\n", ""), "utf-8");
//			}
//			catch (Exception e)
//			{
//				e.printStackTrace();
//			}
		}
		else // text/xml
		{
			System.out.println("getInputStreamAsString:request.getInputStream()");
			StringBuffer sb = new StringBuffer();
			try
			{
			    InputStream in = request.getInputStream();
			    BufferedReader br = new BufferedReader(new InputStreamReader(in));
			    String s;
				while ((s = br.readLine()) != null){
					sb.append(s);
				}
				br.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			string = sb.toString();
		}
		return string;
	}
	
	public static void main (String[] arg)
	{
	}
}
